<?php

    class Linea {
        private $id     = null;
        private $nombre = null;

        function __construct() {}

        function get_id                 () { return $this->id;     }
        function get_nombre             () { return $this->nombre; }

        function set_id                 ( $value ) { $this->id     = $value; }
        function set_nombre             ( $value ) { $this->nombre = $value; }

        static function GetCollection() {
            $dbh = DBH::GetInstance()->get_dbh();

            $q = 'SELECT id, nombre FROM lineas ORDER BY nombre';

            $collection = array();
            foreach( $dbh->query($q) as $row ) {
                $instance = new Linea();
                $instance->set_id( $row['id'] );
                $instance->set_nombre( $row['nombre'] );
                array_push( $collection, $instance );
            }

            return $collection;
        }

        static function GetByID( $id ) {
            $dbh = DBH::GetInstance()->get_dbh();

            $sth = $dbh->prepare('SELECT id, nombre FROM lineas WHERE id = :id');
            $sth->bindParam( ':id', $id, PDO::PARAM_INT );
            $sth->execute();
            $result = $sth->fetch( PDO::FETCH_ASSOC );

            if( ! $result ) return false;

            $instance = new Linea();
            $instance->set_id( $result['id'] );
            $instance->set_nombre( $result['nombre'] );

            return $instance;
        }

        function save() {
            if( ! self::GetByID($this->get_id()) ) return $this->insert();
            else                                   return $this->update();
        }

        private function insert() {
            $dbh = DBH::GetInstance()->get_dbh();
            $sth = $dbh->prepare('INSERT INTO lineas ( nombre ) VALUES ( :nombre )');
            $sth->bindParam( ':nombre', $this->nombre, PDO::PARAM_STR );

            return $sth->execute();
        }

        private function update() {
            $dbh = DBH::GetInstance()->get_dbh();

            $sth = $dbh->prepare('UPDATE lineas SET nombre = :nombre WHERE id = :id');
            $id     = $this->get_id();
            $nombre = $this->get_nombre();
            $sth->bindParam( ':id'    , $id,     PDO::PARAM_INT );
            $sth->bindParam( ':nombre', $nombre, PDO::PARAM_STR );

            return $sth->execute();
        }

        function delete() {
            $dbh = DBH::GetInstance()->get_dbh();

            $sth = $dbh->prepare('DELETE FROM lineas WHERE id = :id');
            $id = $this->get_id();
            $sth->bindParam( ':id', $id, PDO::PARAM_INT );

            return $sth->execute();
        }
    }

?>